<template>
	<uni-popup ref="uniPopup" type="bottom">
		<view class="content bg-white">
			<view class="row-center mb-3">
				<view class="text-hide p-3-1" @click="close"> <text class="text-l color-secondary-2">取消</text> </view>
				<view class="flex-1"></view>
				<view class="text-hide p-3-1" @click="ok"> <text class="text-l color-active">确定</text> </view>
			</view>
			<view class="flex flex-row flex-wrap pl-3-1">
				<view
					style="width: 150rpx"
					class="rounded-l bg-1 text-hide py-1-3 text-center mr-2 mb-2"
					:class="{ 'bg-active': el.selected }"
					v-for="el in innerData"
					:key="el.value"
					@click="toggleItem(el)"
				>
					<text class="text-n color-main" :class="{ 'color-white': el.selected }">{{ el.text }}</text>
				</view>
			</view>
			<view class="p-3-1">
				<c-button @touch="toggleAll">{{ isSelectAll ? '全不选' : '全选' }}</c-button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
import { watch, ref } from 'vue';
export default {
	components: {},
	//change select
	props: {
		data: {
			required: true,
			type: Array,
		},
		unSelectMes: {
			default: '请至少选择一个平台',
			type: String,
		},
	},
	setup(props, context) {
		const uniPopup = ref();
		const innerData = ref(props.data.map((el) => Object.assign({ selected: false }, el)));
		watch(
			() => props.data,
			(v) => {
				innerData.value = v.map((el) => Object.assign({ selected: false }, el));
				isSelectAll.value = false;
			}
		);
		function open() {
			uniPopup.value.open();
		}
		function close() {
			uniPopup.value.close();
		}
		let isSelectAll = ref(false);
		return {
			innerData,
			open,
			close,
			isSelectAll,
			toggleItem(el) {
				el.selected = !el.selected;
				if (el.selected) {
					let hasUnselect = false;
					innerData.value.forEach((el) => {
						if (!el.selected) {
							hasUnselect = true;
							return false;
						}
					});
					isSelectAll.value = !hasUnselect;
				} else {
					isSelectAll.value = false;
				}
			},
			toggleAll() {
				isSelectAll.value = !isSelectAll.value;
				innerData.value.forEach((el) => {
					el.selected = isSelectAll.value;
				});
			},
			ok() {
				const sels = [];
				innerData.value.forEach((el) => {
					if (el.selected) {
						sels.push(el);
					}
				});
				if (sels.length === 0) {
					getApp().globalData.toast(props.unSelectMes);
				} else {
					context.emit('choose', sels);
					close();
				}
			},
			uniPopup,
		};
	},
};
</script>

<style lang="scss">
.content {
	margin-bottom: var(--window-bottom);
}
</style>
